/**
 * Adapter danh sach cac bai hat Online
 */
package com.toidep.adapters;

import java.util.ArrayList;

import android.util.Log;
import android.view.View;
import android.view.ViewGroup;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.ImageView.ScaleType;
import android.widget.TextView;

import com.toidep.R;
import com.toidep.activities.MainActivity;
import com.toidep.api.ApiController;
import com.toidep.api.ParseJSON;
import com.toidep.base.BaseFragment;
import com.toidep.bitmaputil.ImageWorker;
import com.toidep.config.ConfigUtility;
import com.toidep.config.Constants;
import com.toidep.entities.AlbumEntity;
import com.toidep.entities.VideoEntity;
import com.toidep.interfaces.ResponseListener;
import com.toidep.preference.SharePreference;
import com.toidep.widgets.sectionlist.AmazingAdapter;

public class VideoAdapter extends AmazingAdapter{

	private MainActivity mainActivity;
	private BaseFragment parentFragment;
	
	private ArrayList<VideoEntity> listVideo;
	public ArrayList<ViewHolder> arrViewHolder;			// QUan ly cac ViewHolder

	private int adapterTypeByScreen;					// Adapter nay cua Screen nao de goi API tuong ung cho dung
	
	private int typeVideo;								// typeVideo cho api getVideo  = 0: ALL | 1: NEW | 2: HOT | 3: TOP
	private String modelId;								// modelId cho api getVideo cua Model
	private String videoId;								// videoId cho api getVideo lien quan den videoId
	private String keyword;								// keyword cho api Search
	
	/**
	 * Constructor
	 * Khoi tao Adapter lay danh sach Videos
	 * @param ff
	 * @param adapterType Adapter Screen Type
	 * @param typeVideo = All, Top, New, Hot
	 */
	public VideoAdapter(BaseFragment ff, int adapterTypeByScreen, int typeVideo) {
		this.mainActivity = (MainActivity) ff.getActivity();
		this.parentFragment = ff;
		this.listVideo = new ArrayList<VideoEntity>();
		this.arrViewHolder = new ArrayList<ViewHolder>();

		this.adapterTypeByScreen = adapterTypeByScreen;
		if (adapterTypeByScreen == Constants.CATEGORY_VIDEO) {
			this.typeVideo = typeVideo;
		}
	}
	
	/**
	 * Constructor 
	 * Khoi tao Adapter lay danh sach Video cua 1 Model
	 * Khoi tao Adapter lay danh sach Video lien quan den 1 Video
	 * Khoi tao Adapter lay danh sach Video Tim kiem theo keyword
	 * @param ff
	 * @param adapterTypeByScreen
	 * @param stringParam
	 */
	public VideoAdapter(BaseFragment ff, int adapterTypeByScreen, String stringParam) {
		this.mainActivity = (MainActivity) ff.getActivity();
		this.parentFragment = ff;
		this.listVideo = new ArrayList<VideoEntity>();
		this.arrViewHolder = new ArrayList<ViewHolder>();
		
		this.adapterTypeByScreen = adapterTypeByScreen;
		if (adapterTypeByScreen == Constants.CATEGORY_SEARCH) {
			this.keyword = stringParam;
		} else if (adapterTypeByScreen == Constants.CATEGORY_MODEL_DETAL_VIDEO) {
			this.modelId = stringParam;
		} else if (adapterTypeByScreen == Constants.CATEGORY_VIDEO_DETAIL) {
			this.videoId = stringParam;
		}
	}
	
	public ArrayList<VideoEntity> getListVideo() {
		return this.listVideo;
	}
	
	public void resetList(ArrayList<VideoEntity> l) {
		if (listVideo == null) {
			listVideo = new ArrayList<VideoEntity>();
		}
		//===== Tao Mang ViewHolder=====
		if (arrViewHolder == null) {
			arrViewHolder = new ArrayList<ViewHolder>();
		}
		arrViewHolder.clear();
		for (int i = 0; i < l.size(); i++) {
			arrViewHolder.add(null);
		}
		//==============================
		listVideo.clear();
		listVideo.addAll(l);
		notifyDataSetChanged();
	}
	
	public void resetList() {
		if (listVideo == null) {
			listVideo = new ArrayList<VideoEntity>();
		}
		if (arrViewHolder == null) {
			arrViewHolder = new ArrayList<ViewHolder>();
		}
		listVideo.clear();
		
		getFirstPage();
	}
	
	public int getCount() {
		if (listVideo != null)
			return listVideo.size();
		else 
			return 0;
	}

	public VideoEntity getItem(int position) {
		return listVideo.get(position);
	}

	public long getItemId(int position) {
		return position;
	}
	
	// TODO: onNextPageRequested
	@Override
	protected void onNextPageRequested(int page) {
		getVideos(page);
	}

	@Override
	protected void bindSectionHeader(View view, int position, boolean displaySectionHeader) {
		// do nothing
	}
	
	private class ViewHolder {
		public ImageView image;
	}

	@Override
	public View getAmazingView(int position, View convertView, ViewGroup parent) {
		final ViewHolder viewHolder;
		
		int widthImage, heightImage;
		int widthImageView, heightImageView;
		
		final VideoEntity currentItem = getItem(position);
		
		widthImage = ConfigUtility.size_full_width;
		heightImage = (int) (widthImage * ConfigUtility.scale_size_list_horizontal);
		
		widthImageView = ConfigUtility.scrWidth;
		heightImageView = (int) (widthImageView * ConfigUtility.scale_size_list_horizontal);
			
		if (convertView == null) {
			
			convertView = parentFragment.getActivity().getLayoutInflater().inflate(R.layout.layout_itemlist_video, null);
			viewHolder = new ViewHolder();
			viewHolder.image = (ImageView) convertView.findViewById(R.id.imageView);
			
			FrameLayout.LayoutParams layoutParams = new FrameLayout.LayoutParams(widthImageView, heightImageView);
			viewHolder.image.setLayoutParams(layoutParams);
			viewHolder.image.setScaleType(ScaleType.FIT_CENTER);
			
			convertView.setTag(viewHolder);
			
		} else {
			viewHolder = (ViewHolder) convertView.getTag();
		}
		
		// Load avatar
		viewHolder.image.setTag(currentItem.getThumb());
		mainActivity.loadImage(viewHolder.image, currentItem.getThumb(),
				widthImage, heightImage, widthImageView, heightImageView);
		
		// Them vao mang ViewHolder
		try {
			arrViewHolder.set(position, viewHolder);
		} catch (Exception e) {
		}
		
		// Load description
		TextView textDuration = (TextView) convertView.findViewById(R.id.textDuration);
		textDuration.setText(" " + currentItem.getDuration() + " ");
		TextView textName = (TextView) convertView.findViewById(R.id.textName);
		textName.setText(currentItem.getTitle());
		TextView textCommentCount = (TextView) convertView.findViewById(R.id.textCommentCount);
		textCommentCount.setText(currentItem.getTotalComment());
		TextView textViewCount = (TextView) convertView.findViewById(R.id.textViewCount);
		textViewCount.setText(currentItem.getTotalView());
		// Bug #303 - Start
		boolean loginStatus = SharePreference.getInstance(mainActivity)
				.getLoginStatus();
		ImageView imgLock = (ImageView) convertView
				.findViewById(R.id.imageLock);
		if (currentItem.isPayment() && !loginStatus) {
			imgLock.setVisibility(View.VISIBLE);
		} else {
			imgLock.setVisibility(View.GONE);
		}
		// Bug #303 - End
		
		return convertView;
	}

	@Override
	public void configurePinnedHeader(View header, int position, int alpha) {
		
	}

	@Override
	public int getPositionForSection(int section) {
		return 0;
	}

	@Override
	public int getSectionForPosition(int position) {
		return 0;
	}

	@Override
	public int getSectionPosition(int position) {
		return 0;
	}

	@Override
	public Object[] getSections() {
		return null;
	}
	
	/**
	 * Clear Adapter ve null
	 */
	public void clear() {
		resetPage();
		listVideo.clear();
//		listSong = null;
		clearTemporarity();
		notifyDataSetChanged();
	}
	
	/**
	 * Xoa cac bien su dung: ViewHolder...
	 */
	public void clearTemporarity() {
		if (arrViewHolder != null)
			arrViewHolder.clear();
//		arrViewHolder = null;
	}
	
	/**
	 * Cancel cac task load anh khi close fragment
	 */
	public void pauseLoadingImage() {
		if (arrViewHolder != null) {
			for (ViewHolder viewHolder : arrViewHolder) {
				try {
					if (viewHolder.image != null) {
						ImageWorker.cancelWork(viewHolder.image);
					}
				} catch (Exception e) {
				}
			}
		}
	}
	
	/**
	 * Clear memory cache
	 */
	public void clearMemoryCacheOnly() {
		Log.e("SongsAdapter", "clearMemoryCacheOnly");
//		imageFetcher.clearMemoryCacheOnly();
	}
	
	/**
	 * Goi ham nay khi Fragment chua no xay ra onDestroy
	 */
	public void destroyAdapter() {
		clear();
		listVideo = null;
		arrViewHolder = null;
//		imageFetcher = null;
	}
	
	// ======================== GOI API TUONG UNG VOI CAC ADAPTER ==========================
	
	/**
	 * List Videos theo categories NEW - HOT - TOP - ALL
	 * List Videos cua 1 Model
	 * List Videos Lien quan cua 1 Video
	 * List Videos Tim kiem theo keyword
	 */
	private void requestAPI(int page, ResponseListener responseListener) {
		if (adapterTypeByScreen == Constants.CATEGORY_VIDEO) {
			ApiController.getVideosNormal(parentFragment.getActivity(), typeVideo,
					page, ConfigUtility.PAGE_SIZE, responseListener);
		} else if (adapterTypeByScreen == Constants.CATEGORY_MODEL_DETAL_VIDEO) {
			ApiController.getVideosOfModel(parentFragment.getActivity(), modelId, 
					page, ConfigUtility.PAGE_SIZE, responseListener);
		} else if (adapterTypeByScreen == Constants.CATEGORY_VIDEO_DETAIL) {
			ApiController.getRelation(parentFragment.getActivity(), Constants.RELATION_TYPE_VIDEO, videoId, 
					page, ConfigUtility.PAGE_SIZE, responseListener);
		} else if (adapterTypeByScreen == Constants.CATEGORY_SEARCH) {
			ApiController.getSearchContent(parentFragment.getActivity(), Constants.SEARCH_TYPE_VIDEO, keyword, 
					page, ConfigUtility.PAGE_SIZE, responseListener);
		}
	}
	
	private void getVideos(int page) {

		ResponseListener responseListener = new ResponseListener() {
					
			@Override
			public void processResponse(int inintstall) {
				notifyNoMorePages();
			}
			
			@Override
			public void processResponse(String response) {
				if (response != null) {
					try {
						ArrayList<VideoEntity> list = ParseJSON.getAllVideoObjectFromResponse(response);
						if (list != null && list.isEmpty() == false) {
							listVideo.addAll(list);
							//===== Tao Mang ViewHolder=====
							for (int i = 0; i < list.size(); i++) {
								arrViewHolder.add(null);
							}
							//==============================
							nextPage();
							notifyDataSetChanged();
							if (list.size() < ConfigUtility.PAGE_SIZE)
								notifyNoMorePages();
							else
								notifyMayHaveMorePages();
						} else {
							notifyNoMorePages();
						}
					} catch (Exception e) {
						notifyNoMorePages();
					} finally {
						isLoadingMore = false;
					}
				} else {
					notifyNoMorePages();
				}
			}
		};
		
		requestAPI(page, responseListener);
	}
	
	private void getFirstPage() {
		int page = 1;
		ResponseListener responseListener = new ResponseListener() {
			
			@Override
			public void processResponse(int inintstall) {
				notifyNoMorePages();
			}
			
			@Override
			public void processResponse(String response) {
				if (response != null) {
					ArrayList<VideoEntity> list = ParseJSON.getAllVideoObjectFromResponse(response);
					if (list != null && list.isEmpty() == false) {
						notifyMayHaveMorePages();
						
						resetList(list);
					} else {
						notifyNoMorePages();
					}
				} else {
					notifyNoMorePages();
				}
			}
		};

		requestAPI(page, responseListener);
	}

	public void onItemClick(int position) {
		if (getCount() == 0) return;
		mainActivity.openDetailVideo(getItem(position));
		// 14-05-2014 Bugs #303 start.
//		final VideoEntity currentItem = getItem(position);
//		if (!currentItem.isPayment()) {
//			mainActivity.openDetailVideo(getItem(position));
//		}
		// 14-05-2014 End.
	}
}
